import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Tools, Toast,Icon,ActivityIndicator} from 'weaver-mobile'
import { withRouter } from 'react-router-dom';
import DocConstant from '../../util'
import {downloadFile,GetUrlParam,getWpsSign} from '../../util/Utils'
const getLabel = Tools.getLabel;

@withRouter
@inject('attachStore')
@observer
class Attach extends React.Component {
    componentWillUnmount(){
        Toast.hide();
        // 取消浏览器缩放支持
        // var _win = window;
        // while(_win.parent !== _win){
        // _win = _win.parent;
        // }
        let viewport = window.top.document.querySelector("meta[name=viewport]");
        viewport.setAttribute('content', "width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no");
    }
    componentDidMount() {
        const {location,attachStore} = this.props;
        const {pathname} = location
        const paths = pathname.split("/");
        const fileid = paths[paths.length - 1];
        const {search} = location;
        let otherMouldParams = '';
        let urlParams = '';
        attachStore.isConvertFileEnd = false;
        otherMouldParams = DocConstant.getLocationUrlParams(); //嵌套在iframe中传过来的参数
        urlParams = search.slice(search.indexOf('?') + 1);  //通过导航栏链接传过来的参数
        let fromModule = GetUrlParam(search,"fromModule")
        let chagneTopTitle = GetUrlParam(search,"chagneTopTitle")||"true";
        attachStore.fromModule = fromModule ? fromModule : "";
        attachStore.otherMouldUrlParams = !otherMouldParams ? urlParams : otherMouldParams + (!urlParams ? '' : '&') + urlParams;
        attachStore.fileToDocDetail({fileid:fileid,chagneTopTitle},this);
        // var _win = window;
        // while(_win.parent !== _win){
        // _win = _win.parent;
        // }
        //  增加文档页面的浏览器缩放支持
        
        // viewport1.setAttribute('content', "width=device-width,initial-scale=1,maximum-scale=3,minimum-scale=1,user-scalable=yes");
        //window.setTimeout(()=>{
        if(chagneTopTitle!="false"){
            let viewport = window.top.document.querySelector("meta[name=viewport]");
            viewport.setAttribute('content', "width=device-width,initial-scale=0.9,maximum-scale=5,minimum-scale=0.1,user-scalable=yes");
        }
        //}, 1000);
    }
	componentWillReceiveProps(nextProps){
		const {location,attachStore} = nextProps;
        const {pathname} = location
        const paths = pathname.split("/");
        const fileid = paths[paths.length - 1];
        const {search} = location;
        let otherMouldParams = '';
        let urlParams = '';
        attachStore.isConvertFileEnd = false;
        otherMouldParams = DocConstant.getLocationUrlParams(); //嵌套在iframe中传过来的参数
        urlParams = search.slice(search.indexOf('?') + 1);  //通过导航栏链接传过来的参数
        let fromModule = GetUrlParam(search,"fromModule")
        let chagneTopTitle = GetUrlParam(search,"chagneTopTitle")||"true";
        attachStore.fromModule = fromModule ? fromModule : "";
        attachStore.otherMouldUrlParams = !otherMouldParams ? urlParams : otherMouldParams + (!urlParams ? '' : '&') + urlParams;
        attachStore.fileToDocDetail({fileid:fileid,chagneTopTitle},this);
        // var _win = window;
        // while(_win.parent !== _win){
        // _win = _win.parent;
        // }
        //  增加文档页面的浏览器缩放支持
        
        // viewport1.setAttribute('content', "width=device-width,initial-scale=1,maximum-scale=3,minimum-scale=1,user-scalable=yes");
        //window.setTimeout(()=>{
        if(chagneTopTitle!="false"){
            let viewport = window.top.document.querySelector("meta[name=viewport]");
            viewport.setAttribute('content', "width=device-width,initial-scale=0.9,maximum-scale=5,minimum-scale=0.1,user-scalable=yes");
        }
	}
    setiframeHeight = () =>{
        const {attachStore} = this.props,{isUsePoi}=attachStore;
        if(isUsePoi){
            try{
                let iframeList = document.getElementsByTagName("iframe");
                let domNode = iframeList && iframeList[0].contentWindow.document;
                let mainiframe = document.getElementById("mainiframe"),
                iframeclass = document.getElementsByClassName("wm-route-layout")[0],
                domWidth = 0,
                domHight = 0,
                pagewidth = window.innerWidth,
                pageheight = window.innerHeight,
                iframeBodyclass = domNode.getElementsByClassName("b2");
                let d1class = domNode.getElementsByClassName("d1");
                let d2class = domNode.getElementsByClassName("d2");
                if(d1class){
                    for(let i = 0;i<d1class.length;i++){
                        d1class[i].style.margin = "0";
                        d1class[i].style.padding = "10px";
                    }
                }
                if(d2class){
                    for(let i = 0;i<d2class.length;i++){
                        d2class[i].style.margin = "0";
                        d2class[i].style.padding = "10px";
                    }
                }
                for(let i = 0;i<iframeBodyclass.length;i++){
                  iframeBodyclass[i].style.margin = "0";
                  iframeBodyclass[i].style.padding = "10px";
                }
                domWidth = domNode.body.scrollWidth;
                domHight = domNode.body.scrollHeight;
                if (!domNode) return;
                domHight = domHight<pageheight ? pageheight : domHight;
                domWidth = domWidth<pagewidth ?pagewidth : domWidth;
                mainiframe.style.height=domHight+"px";
                // iframeclass.style.width=domWidth+"px";
            } catch(e){
                // 防止跨域报错
            }
        }
        
    }
    setDocLock = () =>{
        setTimeout(()=>{
        try{
            const {attachStore} = this.props;
            let iframeList = document.getElementsByTagName("iframe");
			if(attachStore.docisLock){
			  for(let index =0;index < iframeList.length; index++){
                let domNode = iframeList && iframeList[index].contentWindow.document;
                  if (!domNode) return;
                  if(domNode.body){
                   domNode.body.style.cssText += ';-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;unselectable:on;';
                   domNode.body.onselectstart = function () {return false};
                  }
			  }
			  if(document.body){
			    document.body.style.cssText += ';-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;unselectable:on;';
			    document.body.onselectstart = function () {return false};
			  }
            }
            this.setiframeHeight();
         } catch(e){
        // 防止跨域报错
         }
        },1000
        );
    }


render() {
        const {attachStore,location} = this.props,
        {
            isConvertFileSuccess,
            convertMessage,
            isReadOnline,
            otherMouldUrlParams,
            docInfo,
            attachInfo,
            loading,
            isConvertFileEnd,
            canReader
        } = attachStore;
        const {search} = location
        let urlParams = search.slice(search.indexOf('?') + 1);
        if (loading) {
            return (
              <div className="wea-doc-whitebg">
                <div className="wea-doc-error">
                   <ActivityIndicator size="large"/>
                </div>
              </div>
            );
          }
        if(!canReader){
            return (
                <div className="wea-doc-whitebg">
                    <div className="wea-doc-error">
                    <Icon type="wuquanxian" size="lg" style={{width: 100, height: 100}}/>
                    <div>{getLabel(382663, "暂无权限")}</div>
                    </div>
                </div>
            );
        }
        let iframeParam = {};
        iframeParam = attachStore.isUsePoi?{scrolling:"no"}:{};
        return (
            <div className="wea-doc-bg-attach">
            <div className="wm-route-layout">
                {
                    isReadOnline === '1'
                        ? isConvertFileSuccess
                            ? isConvertFileEnd
                                ? <div className="wea-doc-open-attach"> 
                                    <iframe 
                                        src={attachStore.openAttachPath} 
                                        id="mainiframe"
                                        title={getLabel(388748, "查看文件")} 
                                        frameBorder="0" 
                                        style={{height: '100%', width: '100%'}}
										onLoad={()=>{
											this.setDocLock();
											getWpsSign("mainiframe");
										}}
                                        iframeParam
                                        >
                                    </iframe>
                                   </div>
                                : <div className="wea-doc-error">
                                    <Icon type="cross" size="lg"/>
                                    <div>{convertMessage}</div>
                                 </div>
                            : ''
                        : 
                        <div className="wea-doc-error">
                            <div className="doc-attach-item-download" style={
                                docInfo.candownload 
                                ? attachInfo.readOnLine==='0'
                                    ? (docInfo.doc_acc_isdownload || '1') === '0'
                                        ?{display:'none'}
                                        :{display:'block'}
                                    :{display:'block'}
                                :{display:'none'}}                  
                                    onClick={(e) =>  {
                                    e.stopPropagation();
                                    let url = `/weaver/weaver.file.FileDownload?fileid=${attachInfo.imagefileid}&download=1&from_doc_mobile=1`;
                                    let ddcode = attachInfo.ddcode;
                                    if(ddcode){
                                        url = url + `&ddcode=${ddcode}`;
                                    }
                                    if(otherMouldUrlParams){
                                        url = url + `&${otherMouldUrlParams}`;
                                    }
                                    downloadFile(url,attachInfo.imagefileid);
                                    }}
                                >
                                {<Icon type="download" size="xs" style={{ color:'#000' }}/>}
                                <div style={{ color:'#000',marginTop:'10px' }}>{getLabel(516292,'请下载查看')}</div>
                            </div>
                            {
                                !docInfo.candownload || docInfo.doc_acc_isdownload === '0'
                                ? <div style={{ color:'#000',marginTop:'10px' }}>{getLabel(391351, "您查看的文件不能直接打开，请联系创建人获取权限后下载查看")}</div>
                                :''
                            }
                        </div>
                }
            </div>
            </div>
        );
    }
}
export default Attach